package news.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import news.dao.RoleDao;
import news.model.Menu;
import news.model.Role;
import news.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
@Transactional
public class RoleService {
    @Autowired(required = false)
    RoleDao roleDao;
    public PageInfo<Role> roleList(Role role){
        // pageNum当前页面  pageSize每页大小
        PageHelper.startPage(role.getPageNum(), role.getPageSize());
        List<Role> roles = roleDao.roleList(role);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);

        return pageInfo;
    }

    public List<Menu> menus() {
        return roleDao.menus();
    }

    public void save(Role role, String adminToken) {
        //从token中解析出管理员id
        role.setAdmin(JWTUtil.getAdminByToken(adminToken));
        roleDao.save(role);
        for(Integer menuId : role.getMenuId()){
            roleDao.saveRoleMenu(menuId,role.getId());
        }
    }

    public void delete(Integer id) {
        roleDao.deleteRole(id);

        roleDao.deleteRoleMenu(id);
    }

    public Role findRoleById(Integer id) {
        Role role = roleDao.findRoleById(id);
        Integer[] menuId = new Integer[role.getMenus().size()];
        int i = 0;
        for(Menu menu : role.getMenus()){
            menuId[i++] = menu.getId();
        }
        role.setMenuId(menuId);
        return role;
    }

    public void update(Role role, String adminToken) {
        //1.从token中解析出管理员的id
        role.setAdmin(JWTUtil.getAdminByToken(adminToken));
        //2.修改管理员信息
        roleDao.update(role);
        //3.删除管理员和角色之间的关系
        roleDao.deleteRoleMenu(role.getId());
        //4/添加管理员和角色之间的关系
        for(Integer roleId : role.getMenuId()){
            roleDao.saveRoleMenu(roleId,role.getId());
        }
    }
}
